package cn.mijack.face;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import cn.mijack.face.service.FaceService;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by MiJack on 2016/6/13.
 */
public class DemoActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int GET_IMAGE_VIA_CAMERA = 1;
    public static final String TAG = "DemoActivity";
    public static final String localTempImgDir = "FacePlusPlus";
    public static final String FACE_SET_NAME = "ba6c90e40f1440fabf24fe0b8007fa1c";
    private static final int PICTURE_CHOOSE = 2;
    private ImageView btnTake;
    private ImageView btnChoose;
    ImageView imageView1;
    ImageView imageView2;
    TextView textView;
    TextView textView1;
    TextView textView2;

    View imageView4;
    View imageView5;
    View imageView6;

    ViewGroup layoutMain;
    LinearLayout layoutButton;
    private ProgressDialog progressDialog;
    private View.OnClickListener shareListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String shareContent = "你的照片和" + textView2.getText().toString()
                    + "很像" + textView.getText().toString();
            share(shareContent, v.getId());
        }
    };

    private void share(String shareContent, int id) {

        SHARE share = null;
        switch (id) {
            case R.id.imageView4:
                share = SHARE.WECHAT;
                break;
            case R.id.imageView5:
                share = SHARE.WEIBO;
                break;
            case R.id.imageView6:
                share = SHARE.CIRCLE;
                break;

        }
        if (share == null) {
            return;
        }
        share.share(this,shareContent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
        btnTake = (ImageView) findViewById(R.id.btnTake);
        btnChoose = (ImageView) findViewById(R.id.btnChoose);
        layoutMain = (ViewGroup) findViewById(R.id.layoutMain);
        layoutButton = (LinearLayout) findViewById(R.id.layoutButton);

        imageView1 = (ImageView) findViewById(R.id.imageView1);
        imageView2 = (ImageView) findViewById(R.id.imageView2);
        textView = (TextView) findViewById(R.id.textView);
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

        imageView4 = findViewById(R.id.imageView4);
        imageView5 = findViewById(R.id.imageView5);
        imageView6 = findViewById(R.id.imageView6);

        imageView4.setOnClickListener(shareListener);
        imageView5.setOnClickListener(shareListener);
        imageView6.setOnClickListener(shareListener);
        btnTake.setOnClickListener(this);
        btnChoose.setOnClickListener(this);
        showButton(true);
    }

    private void showButton(boolean b) {
        layoutButton.setVisibility(b ? View.VISIBLE : View.GONE);
        layoutMain.setVisibility(!b ? View.VISIBLE : View.GONE);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (layoutButton.getVisibility() != View.VISIBLE) {
                    showButton(true);
                    return true;
                }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnTake:
                take();
                break;
            case R.id.btnChoose:
                selectImage();
                break;
        }
    }

    private void selectImage() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, PICTURE_CHOOSE);
    }

    private void take() {
//        /先验证手机是否有sdcard
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                File dir = new File(Environment.getExternalStorageDirectory() + "/" + localTempImgDir);
                if (!dir.exists()) dir.mkdirs();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, GET_IMAGE_VIA_CAMERA);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(DemoActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(DemoActivity.this, "没有储存卡", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case GET_IMAGE_VIA_CAMERA:
                    Bundle extras = data.getExtras();
                    Bitmap bmp = extras == null ? null : (Bitmap) extras.get("data");
                    Log.d(TAG, bmp != null ? bmp.toString() : "NULL");
                    if (bmp != null) {
                        startFacePlusPlusActivity(bmp);
                    }
                    break;
                case PICTURE_CHOOSE: {
                    if (data != null) {
                        //The Android api ~~~
                        String fileSrc = data.getDataString().substring("/file:".length() + 1);
                        //Log.d(TAG, "Picture:" + fileSrc);
                        //just read size
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;

                        //scale size to read
                        options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max((double) options.outWidth / 1024f, (double) options.outHeight / 1024f)));
                        options.inJustDecodeBounds = false;
                        bmp = BitmapFactory.decodeFile(fileSrc, options);
                        if (bmp != null) {
                            startFacePlusPlusActivity(bmp);
                        }
                    } else {
                        Log.d(TAG, "idButSelPic Photopicker canceled");
                    }
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void startFacePlusPlusActivity(Bitmap bmp) {
        showButton(false);
        imageView1.setImageBitmap(bmp);
        showProgressDialog();
        FaceService.uploadImage(bmp)
                .subscribeOn(Schedulers.io())
                .flatMap(new Func1<JSONObject, Observable<JSONObject>>() {
                    @Override
                    public Observable<JSONObject> call(JSONObject jsonObject) {
                        JSONObject face = null;
                        try {
                            face = jsonObject.getJSONArray("face").getJSONObject(0);
                            String faceId = face.getString("face_id");
                            Log.d(TAG, "faceId:" + faceId);
                            return FaceService.recognitionSearchByFaceSetName(faceId, FACE_SET_NAME);
                        } catch (JSONException e) {
                            return Observable.error(e);
                        }

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<JSONObject, String>() {
                    @Override
                    public String call(JSONObject jsonObject) {
                        try {
                            JSONArray array = jsonObject.getJSONArray("candidate");
                            JSONObject object = array.getJSONObject(0);
                            textView.setText(getString(R.string.similarity, object.getString("similarity")) + "%");
                            String faceId = object.getString("face_id");
                            return faceId;
                        } catch (Exception e) {
                            return null;
                        }
                    }
                })
                .observeOn(Schedulers.io())
                .flatMap(new Func1<String, Observable<JSONObject>>() {
                    @Override
                    public Observable<JSONObject> call(String faceId) {
                        return FaceService.getFace(faceId);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JSONObject>() {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        try {
                            JSONObject faceInfo = jsonObject.getJSONArray("face_info")
                                    .getJSONObject(0);
                            String personName = faceInfo
                                    .getJSONArray("person").getJSONObject(0)
                                    .getString("person_name");
                            textView2.setText(personName);
                            Picasso.with(imageView2.getContext())
                                    .load(faceInfo.getString("url"))
                                    .into(imageView2);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        hideProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideProgressDialog();
                        showResultDialog(e.getMessage());
                    }
                })
        ;
    }


    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("上传分析中...");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    private void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.hide();
        }
    }

    private void showResultDialog(String string) {
        AlertDialog.Builder builder = new AlertDialog.Builder(DemoActivity.this);
        builder.setTitle("result").setMessage(string)
                .show();
    }
}
